package action

import (
	"hub.hddznet.com/app/framework/app"
	"github.com/gin-gonic/gin"
	"hub.hddznet.com/app/framework/app/engines"
	"time"
	"github.com/skip2/go-qrcode"
	"os"
	"io"
	"bytes"
	"strings"
	"fmt"
)

func init() {
	app.AfterInitConfig(func() {
		// 1. 初始化gin引擎
		engines.RegistGin(gin.Default())
		// 2. 初始化jwt
		if app.MustBool("jwt", "use") {
			InitJwt(app.MustValue("jwt", "cache_file"), app.MustValue("jwt", "secret"), 30*24*time.Hour)
		}
		// 3. 自动生成下载页二维码
		if app.MustBool("app-download", "use") {
			data, err := qrcode.Encode(app.MustValue("app-download", "url"), qrcode.Medium, 512)
			path := app.MustValue("app-download", "dir")
			p1 := path[0:strings.LastIndex(path, "/")]
			os.MkdirAll(p1, os.ModePerm)
			f, err := os.Create(path)
			fmt.Println(err)
			if err == nil {
				io.Copy(f, bytes.NewReader(data))
			}
		}

		// 4. 二维码读取URL路径
		engines.Gin.GET(app.MustValue("system", "api.prefix")+"/download/qrcode.png", func(c *gin.Context) {
			f, _ := os.Open(app.MustValue("app-download", "dir"))
			io.Copy(c.Writer, f)
		})
	})
}
